/**
 * 类型缩小
 * 常见的类型保护又以下几种
 * typeof
 * 平等的缩小（比如===、!==）
 * instanceof 某一个实例是不是某种类型
 * in
 * 等等...
 */

// 1.typeof 类型缩小
type IDType = number | string
function printID(id: IDType) {
    if (typeof id == 'string') {
        console.log(id.toLocaleLowerCase());
    } else {
        console.log(id);
    }
}


// 2.平等的缩小（比如===、!==、==、switch）
type Direction = 'left' | 'right' | 'top' | 'bottom'
function printDirection(direction: Direction) {
    if (direction == 'left') {
        console.log(direction);
    } else {

    }

    switch (direction) {
        case 'left':
            console.log(direction);
            break;
        case 'right':
            console.log(direction);
            break;
        case 'top':
            console.log(direction);
            break;
        case 'bottom':
            console.log(direction);
            break;
        default:
            break;
    }
}

// 3.instanceof
function printTime(time: string | Date) {
    if (time instanceof Date) {
        time.toUTCString()
    } else {
        console.log(time);
    }
}

class Student {
    studying() { }
}

class Teacher {
    teaching() { }
}

function work(p: Student | Teacher) {
    if (p instanceof Student) {
        p.studying()
    } else {
        p.teaching()
    }
}

// 4.in
type Fish = {
    swimming: () => void
}

type Dog = {
    running: () => void
}

const fish: Fish = {
    swimming() {
        console.log('swimming');
    }
}

function walk(animal: Fish | Dog) {
    // animal对象中是否有swimming对象
    if ('swimming' in animal) {
        animal.swimming()
    } else {
        animal.running()
    }
}

export { }